# -*- coding: utf-8 -*-
# author: yiming
# pip install alibabacloud_ecs20140526==2.1.0
import sys
from typing import List

from alibabacloud_ecs20140526 import models as ecs_20140526_models
from alibabacloud_ecs20140526.client import Client as Ecs20140526Client
from alibabacloud_tea_openapi import models as open_api_models
from ipaddress import IPv4Address
import json


class Sample:
    def __init__(self):
        pass

    @staticmethod
    def create_client(
        access_key_id: str,
        access_key_secret: str,
    ) -> Ecs20140526Client:
        """
        使用AK&SK初始化账号Client
        @param access_key_id:
        @param access_key_secret:
        @return: Client
        @throws Exception
        """
        config = open_api_models.Config(
            # 您的AccessKey ID,
            access_key_id=access_key_id,
            # 您的AccessKey Secret,
            access_key_secret=access_key_secret
        )
        # 访问的域名
        config.endpoint = 'ecs-cn-hangzhou.aliyuncs.com'
        return Ecs20140526Client(config)

    @staticmethod
    def main(access_key_id, access_key_secret, ip_dict,) -> dict:
        client = Sample.create_client(access_key_id, access_key_secret)
        describe_instances_request = ecs_20140526_models.DescribeInstancesRequest(
            region_id="cn-hangzhou",
            private_ip_addresses=ip_dict.get('inner_ip'),
            # private_ip_addresses=["172.28.20.209"],
            eip_addresses=ip_dict.get('public_ip'),
            page_size=100
        )
        # 复制代码运行请自行打印 API 的返回值
        result = client.describe_instances(describe_instances_request)
        # print(result)
        # instances = result.body.instances.instance
        # print(instances)
        # for instance in instances:
        #     print(f'所属账号 尚娱软件 主机名 {instance.host_name} 实例ID {instance.instance_id} CPU:{instance.cpu}  内存:{instance.memory} MB 规格：{instance.instance_type} 系统:{instance.ostype}({instance.osname}) 状态：{instance.status}')
        return result.to_map()

    def main_inteface(access_key_id, access_key_secret) -> dict:
        client = Sample.create_client('access_key_id', 'access_key_secret')
        describe_network_interface_attribute_request = ecs_20140526_models.DescribeNetworkInterfaceAttributeRequest(
            region_id='cn-hangzhou',
            # network_interface_id='eni-bp14u5el13jpsuo1hx49'
        )
        # 复制代码运行请自行打印 API 的返回值
        client.describe_network_interface_attribute(describe_network_interface_attribute_request)


def ecs_account(account_name, account_id, result, input_address):
    # print(result)
    ecs_account_list = {}
    ecs_list = result.get('body').get('Instances').get('Instance')
    # print(ecs_list)
    if ecs_list:
        eni_list = result.get('body').get('Instances').get('Instance')[0].get('NetworkInterfaces').get('NetworkInterface')
        # print(eni_list)
        networkinterface = []
        index = 0
        while index < len(eni_list):
            # print(eni_list[index].get('PrimaryIpAddress'))
            interface_dict = {key: value for key, value in eni_list[index].items() if (key == 'Type' or key == 'PrimaryIpAddress' or key == 'NetworkInterfaceId')}
            # print(interface_dict)
            # print(eni_list[index].get('Type'))
            networkinterface.append(interface_dict)
            index += 1
        # ipAndInerface = {input_address: networkinterface}
        # print(networkinterface)
        # print(eni_list)
        ecs_account_list = {}
        for i in ecs_list:
            ecs_account_list = {
                "status": "",  # 默认为False,
                "message": "",
                "result": [{
                    "input": input_address,
                    "company": "阿里云",
                    "account_id": account_id,
                    "account_name": account_name,
                    "region": i.get('RegionId'),
                    "product_type": "ECS",
                    "instance_id": i.get('InstanceId'),
                    "instance_name": i.get('InstanceName'),
                    "other": "CPU:" + str(i.get('Cpu')) + "\r\n" +
                             "内存:" + str(i.get('Memory')) + "MB\r\n" +
                             "规格:" + str(i.get('InstanceType')) + "\r\n" +
                             "系统:" + str(i.get('OSName')) + "\r\n" +
                             "状态:" + str(i.get('Status')) + "\r\n" +
                             "弹性网卡数量:" + str(len(eni_list)) + "个" + "\r\n"
                             "弹性网卡详情" + str(networkinterface)
            }]
            }
        # print(ecs_account_list)
    return ecs_account_list


def all_account_list():
    # account_list = []
    for i in ak:
        account_id = i.get('account_id')
        account_name = i.get('account_name')
        access_key_id = i.get('access_key_id')
        access_key_secret = i.get('access_key_secret')
        result = Sample.main(access_key_id, access_key_secret, ip_dict,)
        ip_account_list = ecs_account(account_name, account_id, result, input_address)
        # account_list += ip_account_list
        # print(bool(account_list))
        if ip_account_list:
            break
        else:
            continue
    # print(ip_account_list)
    return ip_account_list


ak = [
    {
      "account_id": "", # 阿里云账号ID
      "account_name": "", #阿里云账号名
      "access_key_id": "", # 您的AccessKey ID
      "access_key_secret": "" # 您的AccessKey Secret
    }
  ]


if __name__ == '__main__':
    # inner_ip_json = {}
    # public_ip_json = {}
    ip_dict = {}
    input_address = input("请输入您要查询的IP\n")
    ip_judge = IPv4Address(input_address).is_private
    if ip_judge:
        inner_ip = input_address
        # inner_ip_json = json.dumps([inner_ip])
        ip_dict["inner_ip"] = json.dumps([inner_ip])
    else:
        public_ip = input_address
        # public_ip_json = json.dumps([public_ip])
        ip_dict["public_ip"] = json.dumps([public_ip])

    account_info = all_account_list()
    # print(account_info)
    if account_info:
        account_info['status'] = True
        account_info['message'] = "查询到一个结果，如下"
        print(account_info)
    else:
        account_info['status'] = False
        account_info['message'] = "没有查询到相关的ECS"
        account_info['result'] = []
        print(account_info)

